package com.example.hf_v1.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import com.example.hf_v1.config.Result;
import com.example.hf_v1.entity.User;
import com.example.hf_v1.entity.po.UserLogin;
import com.example.hf_v1.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/users")

public class UserController {
    @Resource
    private UserService userService;

    //登录接口
    @RequestMapping("/login")
    public Result login(String username, String password) {
        if ((userService.lambdaQuery()
                .eq(username!=null, User::getUsername, username)
                .eq(password!=null, User::getPassword, password)
                .exists())){
            return Result.successLogin((userService.lambdaQuery()
                    .eq(username!=null, User::getUsername, username)
                    .eq(password!=null, User::getPassword, password)
                    .exists()));
        }
        return Result.errorLogin("账号或密码错误");
    }
    //查询所有用户
    @RequestMapping("/selectAllUser")
    public Result selectAllUser() {
        return Result.success(userService.selectAllUser());
    }
    //查询单个用户
    @RequestMapping("/selectUserByUsername")
    public Result selectUserById(UserLogin user) {
        return Result.success(userService.lambdaQuery().eq(User::getUsername, user.getUserName()).list());
    }



    //用户注册接口
    @RequestMapping("/register")
    public Result register(@RequestBody User user) {
        return Result.success(userService.save(user));
    }
    //用户注销接口
    @RequestMapping("/logout")
    public Result logout(Integer id)
    {
        return Result.success(userService.removeById(id));
    }
    //用户修改接口
    @RequestMapping("/updateUser")
    public Result updateUser(@RequestBody User user) {

        return Result.success(userService.updateById(user));
    }
    //获取验证码
    @RequestMapping("/getVerificationCode")
    public Result getVerificationCode() {
        // 自定义纯数字的验证码（随机4位数字，可重复）
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        lineCaptcha.setGenerator(randomGenerator);
        // 重新生成code
        lineCaptcha.createCode();
        return Result.success(lineCaptcha.getCode());

    }

}
